package com.lagou.java.config;

import com.lagou.java.pojo.Configration;
import com.lagou.java.pojo.MapStatement;
import lombok.*;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.InputStream;
import java.util.List;

@ToString
@NoArgsConstructor
@AllArgsConstructor
@Setter
@Getter
public class XMLMapperBuilder {

    private Configration configration;

    public void parse (InputStream inputStream) throws DocumentException {
        Document document = new SAXReader().read(inputStream);
        Element rootElement = document.getRootElement();
        List<Element> list = rootElement.selectNodes("//select");
        list.addAll(rootElement.selectNodes("//update"));
        list.addAll(rootElement.selectNodes("//delete"));
        list.addAll(rootElement.selectNodes("//insert"));

        String namespace = rootElement.attributeValue("namespace");
        for (Element element : list) {
            String id = element.attributeValue("id");
            String resultType = element.attributeValue("resultType");
            String parameterType = element.attributeValue("parameterType");
            String sqlText = element.getTextTrim();
            MapStatement mapStatement = new MapStatement(id, resultType, parameterType, sqlText);
            String key = namespace + "." + id;
            configration.getStatementMap().put(key, mapStatement);
        }
    }
}
